import numpy as np
import csv


def load_data(file_path):
    """
    Load repository data and calculate activity metrics
    Columns: repo_name,owner,stars,forks,language,created_at,last_commit,description
    Return: 2D NumPy array of shape (repos, 3) containing [stars, forks, active_days]

    加载仓库数据并计算活跃天数
    列：仓库名称,所有者,星标,分支,语言,创建时间,最后提交,描述
    返回：形状为(仓库数, 3)的数组，包含[星标数, 分支数, 活跃天数]
    """
    data = []
    with open(file_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        next(reader)  # 跳过标题行
        for row in reader:
            stars = int(row[2])
            forks = int(row[3])
            created_at = np.datetime64(row[5])
            last_commit = np.datetime64(row[6])
            active_days = (last_commit - created_at).astype(int)
            data.append([stars, forks, active_days])
    return np.array(data)


def calculate_statistics(data):
    """
    Calculate repository metrics statistics
    Return: Dictionary containing {
    'means': [stars_mean, forks_mean, days_mean],
    'medians': [stars_median, forks_median, days_median],
    'variances': [stars_var, forks_var, days_var],
    'stds': [stars_std, forks_std, days_std]
    }

    计算仓库指标统计量
    返回：包含平均值、中位数、方差、标准差的字典
    """
    means = np.round(np.mean(data, axis=0), 1)
    medians = np.round(np.median(data, axis=0), 1)
    variances = np.round(np.var(data, axis=0), 1)
    stds = np.round(np.std(data, axis=0), 1)

    return {
        'means': means,
        'medians': medians,
        'variances': variances,
        'stds': stds
    }


def print_results(stats):
    """
    Print formatted results with proper indentation

    按严格格式打印结果，保持正确缩进
    """
    metrics = ['Stars', 'Forks', 'Active Days']
    for metric, mean, med, var, std in zip(metrics,
                                           stats['means'],
                                           stats['medians'],
                                           stats['variances'],
                                           stats['stds']):
        print(f"{metric}:")
        print(f"    Average: {mean:.1f}")
        print(f"    Median: {med:.1f}")
        print(f"    Variance: {var:.1f}")
        print(f"    Standard Deviation: {std:.1f}")


# 假设数据保存为 pakistan-repos.csv 文件
with open('pakistan-repos.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['repo_name', 'owner', 'stars', 'forks', 'language', 'created_at', 'last_commit', 'description'])
    data = """chai-compiler,IndusValleyLabs,765,210,Rust,2023-04-01,2024-03-15,"Compiler for a domain-specific language for Islamic finance."
biryani-cms,IndusValleyLabs,1345,678,PHP,2022-12-01,2024-03-01,"Flexible CMS with multilingual support and Islamic calendar integration."
lahore-os,IndusValleyLabs,678,123,C,2023-08-15,2024-02-20,"Lightweight real-time operating system for embedded devices."
pakistan-nlp,IndusValleyLabs,1234,567,Python,2023-02-10,2024-03-25,"Natural language processing library for Urdu and other regional languages."
karachi-api,IndusValleyLabs,567,89,Go,2024-01-10,2024-03-10,"API gateway with rate limiting and authentication for microservices."
sindh-sdk,IndusValleyLabs,890,345,Java,2023-06-05,2024-01-30,"Software development kit for building mobile apps in the Sindh province."
samosa-vm,IndusValleyLabs,345,90,C++,2022-11-20,2024-03-05,"Virtual machine optimized for running legacy code on modern hardware."
mango-db,IndusValleyLabs,901,456,Scala,2023-09-22,2024-02-28,"Distributed database with ACID properties for transactional applications."
pakhtun-font,IndusValleyLabs,234,78,JavaScript,2024-02-01,2024-03-18,"Web font library for the Pashto language, with various styles."
balochi-chatbot,IndusValleyLabs,456,12,Python,2023-03-01,2024-02-15,"AI-powered chatbot that can understand and respond in Balochi."
shalwar-ide,IndusValleyLabs,789,34,TypeScript,2022-10-10,2024-03-01,"Integrated development environment for web and mobile application development."
cricket-sim,IndusValleyLabs,12,56,C#,2023-05-15,2024-02-01,"Realistic cricket simulation game engine."
pakora-server,IndusValleyLabs,56,78,Kotlin,2023-12-05,2024-03-20,"Lightweight web server for serving static content and REST APIs."
badam-search,IndusValleyLabs,345,90,Go,2022-07-04,2024-02-10,"Full-text search engine optimized for Urdu and other right-to-left languages."
jalebi-ml,IndusValleyLabs,678,23,R,2023-01-01,2024-03-12,"Machine learning library for predictive analytics and data mining."
truck-router,IndusValleyLabs,890,45,Java,2023-11-11,2024-01-25,"Route optimization algorithm for truck drivers in Pakistan."
chaiwala-api,IndusValleyLabs,101,67,Python,2024-02-15,2024-03-08,"API for ordering and tracking chai deliveries."
masala-os,IndusValleyLabs,212,89,Assembly,2023-07-07,2024-02-01,"Minimalist operating system for IoT devices with low power consumption."
halwa-ui,IndusValleyLabs,323,10,JavaScript,2022-09-18,2024-03-05,"UI component library inspired by Pakistani art and architecture."
desi-ai,IndusValleyLabs,434,21,Python,2023-04-20,2024-02-12,"AI framework for building intelligent systems tailored to the Pakistani market."""
    for line in data.splitlines():
        writer.writerow(line.split(','))

repo_data = load_data('pakistan-repos.csv')
stats = calculate_statistics(repo_data)
print_results(stats)